<?php

class RechargeService
{
    /**
     * @var RechargeService
     */
    private static $instance;

    /**
     * Get the instance of RechargeService
     * @return RechargeService
     */
    public static function get()
    {
        if (!self::$instance) {
            self::$instance = new RechargeService();
        }
        return self::$instance;
    }

    /**
     * Construction.
     */
    public function __construct()
    {

    }

    /**
     * @param $userId
     * @param $indexId
     * @param $sign
     * @param $signTime
     * @return bool
     * @throws SzException
     */
    public function reward($userId,$indexId,$sign,$signTime)
    {
        $platform = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_USER_PLATFORM);
        if ($platform == 'wanba'){
            return false;
        }

        if ($platform == 'H5WeChat' || $platform == 'qq'){
            if (!CommonFunctionService::get()->redisFlagCheck(GameConst::CACHE_KEY_RECHARGE_REWARD,$userId,$signTime)) {
                throw new SzException(90111);
            }

            if (!CommonFunctionService::get()->checkMd5($sign,$signTime)){
                throw new SzException(90110);
            }
        }

        $diamondSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_VALUE, $indexId, true);
        if (!$diamondSetting) {
            return false;
        }

        // 每日礼包 && 每周礼包
        if ($diamondSetting['type'] == 6 || $diamondSetting['type'] == 9) {
            /**
             * @var  $dailyGiftPackList DailyGiftPackVoList
             * @var $dailyGiftPack DailyGiftPackVo
             */
            $reqTime = GameService::get()->getReqTime();
            $dailyGiftPackList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_DAILY_GIFT_PACK);
            $dailyGiftPack = $dailyGiftPackList->getElement($indexId,false);
            if (!$dailyGiftPack) {
                $dailyGiftPack = new DailyGiftPackVo($userId,$indexId,0,true);
            }

            $updateTime = $dailyGiftPack->getUpdateTime();
            if($diamondSetting['type'] == 6) {
                if (date('Ymd',$updateTime) == date('Ymd',$reqTime)) {
                    return false;
                }
            }

            if($diamondSetting['type'] == 9) {
                $weekday = date('w');
                $weekday = ($weekday + 6) % 7;
                $date = date('Y-m-d',strtotime("-{$weekday} day"));
                $startTime = strtotime($date);
                $endTime = $startTime + 86400 * 7;
                if ($startTime <= $updateTime && $updateTime < $endTime) {
                    return false;
                }
            }

            $dailyGiftPack->setUpdateTime($reqTime);
            if ($dailyGiftPack->isInsert() && !SzUtility::checkArrayKey($indexId, $dailyGiftPackList->getList())) {
                $dailyGiftPackList->addElement($dailyGiftPack);
                $dailyGiftPackList->setElement($indexId,$dailyGiftPack);
            } else {
                $dailyGiftPackList->updateElement($indexId,$dailyGiftPack);
            }
            SzPersister::get()->setVoList($dailyGiftPackList);
        }

        // 周年庆
        if ($diamondSetting['type'] == 13) {
            //验证活动是否开启
            $anniversaryAid = ActivityAnniversaryService::get()->getAnniversaryIndexId($userId);
            if ($anniversaryAid) {
                /**
                 * @var AnniversaryStepVoList $anniversaryStepList
                 * @var AnniversaryStepVo $anniversaryStep
                 */
                //获取玩家当前购买阶梯礼包的数据
                $anniversaryStepList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ACTIVITY_ANNIVERSARY_STEP);
                $anniversaryStep = $anniversaryStepList->getElement($anniversaryAid,false);
                if ($anniversaryStep){
                    $step = $anniversaryStep->getBuyStep();
                    if ($step + 10000 == $diamondSetting['order']){
                        $remarks = '';
                        $serverTime = GameService::get()->getReqTime();
                        $oldGifts = json_decode($anniversaryStep->getRemarks());
                        if (empty($oldGifts) || $oldGifts == ''|| $oldGifts == null || !$oldGifts){
                            $remarks = (string)$indexId;
                        }
                        else{
                            $remarks = $oldGifts.','.$indexId;
                        }

                        //修改数据
                        $anniversaryStep->setBuyStep($step + 1);
                        $anniversaryStep->setUpdateTime($serverTime);
                        $anniversaryStep->setRemarks($remarks);
                        $anniversaryStepList->updateElement($anniversaryAid,$anniversaryStep);
                        SzPersister::get()->setVoList($anniversaryStepList);
                    }
                    else{
                        return false;
                    }
                }
            }
        }

        // 基金成长
        if ($diamondSetting['type'] == 17) {
            /**
             * @var FundInfoVoList $fundInfoList
             * @var FundInfoVo $fundInfo
             */
            $fundInfoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_FUND_INFO);
            $fundInfo = $fundInfoList->getElement($diamondSetting['indexId'],false);
            if ($fundInfo) {
                $fundInfo->setStatus(1);
                $fundInfoList->updateElement($diamondSetting['indexId'],$fundInfo);
                SzPersister::get()->setVoList($fundInfoList);
            }
        }

        //合约系统
        if ($diamondSetting['type'] == 15 || $diamondSetting['type'] == 16) {
            //平台活动时间区分
            $platform = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_USER_PLATFORM);
            $platformPre = GameConst::PLATFORM_TIME_ARRAY[$platform];
            //获取合约系统的相关配置
            $contractConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_EVENT, null, true);
            //当前时间获取
            $nowTime = GameService::get()->getReqTime();
            $useConf = array();
            $contractStart = 0;
            $contractEnd = 0;
            $isNomal = false;
            $isPoint = false;
            $changeTime = GameService::get()->getReqTime();

            foreach ($contractConf as $aid=>$conf){
                if ($conf['functionId'] == GameConst::FUNC_CONTRACT_FUNC){
                    //验证合约期数是否正确
                    if ($platform != 'dev'){
                        $contractStart = strtotime($conf[$platformPre.'TriggerTime']);
                        $contractEnd = strtotime($conf[$platformPre.'EndTime']);
                    }
                    else{
                        $contractStart = $conf['startTime'];
                        $contractEnd = $conf['endTime'];
//test0813
                        $contractStart = strtotime($conf['weixinTriggerTime']);
                        $contractEnd = strtotime($conf['weixinEndTime']);
                    }

                    if ($nowTime >= $contractStart && $nowTime <= $contractEnd){
                        $useConf = $conf;
                        if ($diamondSetting['type'] == 15){
                            $isNomal = true;
                        }
                        if ($diamondSetting['type'] == 16){
                            $isPoint = true;
                        }
                        break;
                    }
                }
            }

            if ($useConf) {
                //获取玩家等级
                $userLevel = UserService::get()->getUserLevel($userId);
                //获取玩家和合约数据
                /**
                 * @var $contractRewardList ContractRewardVoList
                 * @var $contractReward ContractRewardVo
                 */
                $contractRewardList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_CONTRACT_REWARD);
                $contractReward = $contractRewardList->getElement($useConf['indexId'],false);
                if ($isNomal){
                    if ($contractReward){
                        ContractService::get()->setSeniorSituation($userId,$useConf['indexId'],$nowTime);
                    }

                    StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
                        'clientData' => array(
                            'tid' => 'Module:cash|action:contract|',
                            'item' => 'userLevel&'.$userLevel,
                            'value' => 1
                        )
                    ));
                }

                if ($isPoint){
                    $needPoint = SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'contractLevelup', true);
                    //获取玩家合约数据
                    /**
                     * @var $contractDataList ContractDataVoList
                     * @var $contractData ContractDataVo
                     */
                    $contractDataList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_CONTRACT_DATA);
                    $contractData = $contractDataList->getElement($useConf['indexId'],false);
                    //积分配置处理
                    $point = 0;
                    $pointReward = explode(';',$diamondSetting['specialId']);
                    foreach ($pointReward as $key=>$msg){
                        $specialItem = explode(':',$msg);
                        if ($specialItem[0] == GameConst::SPECIAL_ITEM_TYPE_1){
                            $point += $specialItem[1];
                        }
                    }

                    if ($point){
                        //增加合约积分
                        $hasPoint = $contractData->getNowPoint();
                        $totalPoint = $contractData->getPoint();
                        $nowLevel = $newLevel  = $contractData->getLevel();
                        if ($hasPoint + $point >= $needPoint['value']){
                            $contractData->setNowPoint($hasPoint + $point - $needPoint['value']);
                            $contractData->setLevel($nowLevel + 1);
                            $newLevel = $nowLevel + 1;
                        }
                        else{
                            $contractData->setNowPoint($hasPoint + $point);
                        }
                        $contractData->setPoint($totalPoint + $point);
                        $contractData->setUpdateTime($changeTime);
                        $contractDataList->updateElement($useConf['indexId'],$contractData);
                        SzPersister::get()->setVoList($contractDataList);

                        //领奖状态修改
                        if ($newLevel == $nowLevel + 1){
                            $isSenior = $contractReward->getSenior();
                            if ($isSenior){
                                //高级奖励状态解锁
                                $seniorSituation = explode(',',json_decode($contractReward->getSeniorSituation()));
                                $seniorSituation[$newLevel - 1] = 1;
                                $contractReward->setSeniorSituation(implode(',',$seniorSituation));
                            }

                            //普通奖励状态解锁
                            $generalSituation = explode(',',json_decode($contractReward->getGeneralSituation()));
                            $generalSituation[$newLevel - 1] = 1;
                            $contractReward->setGeneralSituation(implode(',',$generalSituation));
                            $contractReward->setUpdateTime($changeTime);

                            $contractRewardList->updateElement($useConf['indexId'],$contractReward);
                            SzPersister::get()->setVoList($contractRewardList);
                        }

                        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
                            'clientData' => array(
                                'tid' => 'Module:cash|action:point|',
                                'item' => 'userLevel&'.$userLevel,
                                'value' => 1
                            )
                        ));
                    }
                }
            }
        }

        // 扣除钻石
        if ($indexId == 2002){
            //获取玩家数据
            /**
             * @var ModuleProfileVo $profile
             * @var ModuleProfileInfoVoList $profileInfoList
             */
            $profileInfoList = SzPersister::get()->getVoList($userId, ModuleProfileConst::ORM_NAME_PROFILE_INFO);

            $profileFlag = $profileInfoList->getElement(GameConst::USER_INFO_TYPE_SKIP_VIDEO_CARD_FIRST,false);
            if (!$profileFlag){
                //获取首次折扣
                $sale = SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'videoCard', true);
                $num = ceil($diamondSetting['price']*($sale['value']/100));
                if ($num < 10){
                    $num = 10;
                }
                GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_CONSUME_MONEY, $num, true);
                //获得标记
                $profileFlag = new ModuleProfileInfoVo(
                    $userId,
                    GameConst::USER_INFO_TYPE_SKIP_VIDEO_CARD_FIRST,
                    1,
                    time(),
                    true
                );
                $profileInfoList->addElement($profileFlag);
                $profileInfoList->setElement(GameConst::USER_INFO_TYPE_SKIP_VIDEO_CARD_FIRST, $profileFlag);
            }
            else{
                GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_CONSUME_MONEY, $diamondSetting['price'], true);
            }
        }
        else{
                GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_CONSUME_MONEY, $diamondSetting['price'], true);
        }
//        GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_CONSUME_MONEY, $diamondSetting['price'], true);

        $outputTid = '';
        foreach ($diamondSetting['item'] as $entityId => $count) {
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            $outputTid .= $entityId . ':' . $count . '|';
        }

        // 数据采集:行为
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:cash|action:exchange|',
                'item' => $indexId,
                'value' => 1
            )
        ));

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USE_GOLD, array(
            'clientData' => array(
                'item' => 'cash&exchange&' . $indexId,
                'value' => $diamondSetting['price']
            )
        ));

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' => $outputTid,
                'item' => 'cash&exchange&' . $indexId,
            )
        ));

        CommonFunctionService::get()->reportResourceUseDetails(99999972,$userId,1,$outputTid,'reward');//获得资源上报


        return true;
    }

    /**
     * 购买礼包
     * @param $userId
     * @param $giftPackageId
     * @param $reqTime
     * @param $sign
     * @return bool
     * @throws SzException
     */
    public function buyGiftPack($userId, $giftPackageId, $reqTime,$sign)
    {
        $platform = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_USER_PLATFORM);
        if ($platform == 'wanba'){
            return false;
        }

        if ($platform == 'H5WeChat' || $platform == 'qq'){
            if (!CommonFunctionService::get()->redisFlagCheck(GameConst::CACHE_KEY_RECHARGE_GIFT_PACK,$userId,$reqTime)) {
                throw new SzException(90111);
            }

            if (!CommonFunctionService::get()->checkMd5($sign,$reqTime)){
                throw new SzException(90110);
            }
        }

        $diamondGiftPackSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_GIFT_PACK, $giftPackageId, true);
        if (!$diamondGiftPackSetting) {
            return false;
        }
        /**
         * @var $userGiftPackList GiftPackVoList
         * @var $userGiftPack GiftPackVo
         */
        $userGiftPackList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_GIFT_PACK);
        $userGiftPack = $userGiftPackList->getElement($giftPackageId, false);

        //获取巡回礼包配置
        $tourGiftConfs = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_TOUR, null, true,false);
        if (!$tourGiftConfs || empty($tourGiftConfs)){
            return true;
        }

        //获取使用配置
        $key = 0;
        $useConf = array();
        $needGiftArr = array();
        foreach ($tourGiftConfs as $id=>$data){
            if (in_array($giftPackageId,$data['giftId'])){
                $key = $id;
                $useConf = $data;
                $needGiftArr = $data['giftId'];
                break;
            }
        }

        $isCreat = false;
        if (!in_array($giftPackageId,$needGiftArr)){
            if (!$userGiftPack) {
                return false;
            }

            if ($userGiftPack->getStatus()) {
                return false;
            }

            if ($diamondGiftPackSetting['type'] != 4) {
                if ($reqTime < $userGiftPack->getStartTime() || $reqTime > ($userGiftPack->getEndTime() + 600)) {
                    return false;
                }
            }
        }
        else{
            if ($userGiftPack) {
                $userGiftPack->setStatus(1);
            }
            else{
                $isCreat = true;
                $userGiftPack = new GiftPackVo(
                    $userId,
                    $giftPackageId,
                    1,
                    $reqTime,
                    0,
                    true
                );
            }
        }

        // 扣除钻石
        GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_CONSUME_MONEY, $diamondGiftPackSetting['price'], true);

        $outputTid = '';
        $diamond = 0;
        /**
         * @var ModuleItemVoList $itemList
         */
        $itemList = null;
        $index = 0;
        foreach ($diamondGiftPackSetting['rewardProps'] as $entityId => $count) {
            $index++;
            if ($diamondGiftPackSetting['type'] == 3) {//组合礼包
                $itemList = is_null($itemList) ? SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM) : $itemList;
                list($action, $module, $itemDefId) = EntityService::get()->parseEntityId($entityId);
                if ($action == GameConst::ENTITY_ACTION_GET && $module == GameConst::ENTITY_TYPE_ITEM) {
                    $itemSetting = SzConfig::get()->loadAppConfig(ModuleItemConst::CONFIG_ITEM_DEFS, $itemDefId, true);
                    if ($itemSetting['category'] == GameConst::ITEM_CATEGORY_CULTIVATE_CARD) {
                        $item = $itemList->getElementsByItemDefId($itemDefId);
                        if ($item) {//组合礼包中如果有培育卡且已经获得过则换成对应的钻石
                            $diamond += $diamondGiftPackSetting['conversionRatio'][$index - 1];
                            continue;
                        }
                    }
                }
            }
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            $outputTid .= $entityId . ':' . $count . '|';
        }

        foreach ($diamondGiftPackSetting['diamond'] as $entityId => $count) {
            if ($entityId == GameConst::ENTITY_ACTION_GET_MONEY && $count > 0) {
                $diamond += $count;
            }
        }

        if ($diamond > 0) {
            GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_GET_MONEY, $diamond, true);
            $outputTid .= GameConst::ENTITY_ACTION_GET_MONEY . ':' . $diamond . '|';
        }

        //装饰物礼包的处理
        if ($diamondGiftPackSetting['type'] == 8) {
            $trimmingRewardInfo = explode(':',$diamondGiftPackSetting['specialId']);
            if ($trimmingRewardInfo[0]==GameConst::SPECIAL_ITEM_TYPE_2) {
                $trimmingReward = explode(',',$trimmingRewardInfo[1]);
                $profileInfoList = SzPersister::get()->getVoList($userId, ModuleProfileConst::ORM_NAME_PROFILE_INFO);
                $trimmingInfo = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_TRIMMING_INFO, $profileInfoList);
                if (is_null($trimmingInfo)) {
                    $trimmingInfo = [];
                }
                foreach ($trimmingReward as $key=>$trimmingId){
                    if (!in_array($trimmingId, $trimmingInfo)) {
                        $trimmingInfo[] = (int)$trimmingId;
                    }
                }
                UserService::get()->updateProfileInfo($userId, GameConst::USER_INFO_TYPE_TRIMMING_INFO, $trimmingInfo, $profileInfoList);
            }

        }

        if ($isCreat){
            $userGiftPackList->addElement($userGiftPack);
            $userGiftPackList->setElement($giftPackageId, $userGiftPack);
        }
        else{
            $userGiftPack->setStatus(1);
            $userGiftPackList->updateElement($giftPackageId, $userGiftPack);
        }

        SzPersister::get()->setVoList($userGiftPackList);

        if (empty($key) || empty($useConf) || empty($needGiftArr)){
            return true;
        }

        /**
         * @var TourGiftVoList $tourGiftList
         * @var TourGiftVo $tourGiftInfo
         */
        //获取玩家巡回礼包数据
        $tourGiftList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_TOUR_GIFT);
        $tourGiftInfo = $tourGiftList->getElement($useConf['id'],false);

        if (!$tourGiftInfo){//新建巡回礼包数据
            $tourGiftInfo = new TourGiftVo(
                $userId,
                $useConf['id'],
                json_encode((string)$giftPackageId),
                json_encode('0,0'),
                $reqTime,
                0,
                true
            );
        }
        else{
            $num = 0;
            $buyInfo = json_decode($tourGiftInfo->getBuySituation());
            if (!empty($buyInfo) || $buyInfo != ''){
                $bugArr = explode(',',$buyInfo);
                if (!in_array($giftPackageId,$bugArr)){
                    $num =  count($bugArr) + 1;
                }else{
                    $num = count($bugArr);
                }
            }
            if ($num == 0 || $num == 1){
                $tourGiftInfo->setBuySituation((string)$giftPackageId);
                $tourGiftInfo->setRewardSituation('0,0');
            }
            else{
                $tourGiftInfo->setBuySituation($buyInfo.','.$giftPackageId);
                $getSituation = json_decode($tourGiftInfo->getRewardSituation());
                $getSituationArr = explode(',',$getSituation);
                if ($num == 2){
                    if ($getSituationArr[0] != 2){
                        $getSituationArr[0] = 1;
                    }
                }
                if ($num == 3){
                    if ($getSituationArr[1] != 2){
                        $getSituationArr[1] = 1;
                    }
                }

                $tourGiftInfo->setRewardSituation(implode(',',$getSituationArr));
            }
        }

        if ($tourGiftInfo->isInsert() && !SzUtility::checkArrayKey($useConf['id'], $tourGiftList->getList())) {
            $tourGiftList->addElement($tourGiftInfo);
            $tourGiftList->setElement($useConf['id'],$tourGiftInfo);
        }
        else{
            $tourGiftList->updateElement($useConf['id'],$tourGiftInfo);
        }

        SzPersister::get()->setVoList($tourGiftList);

        // 数据采集:行为
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:cash|action:exchange|',
                'item' => $giftPackageId,
                'value' => 1
            )
        ));

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USE_GOLD, array(
            'clientData' => array(
                'item' => 'cash&exchange&' . $giftPackageId,
                'value' => $diamondGiftPackSetting['price']
            )
        ));

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' => $outputTid,
                'item' => 'cash&exchange&' . $giftPackageId,
            )
        ));

        CommonFunctionService::get()->reportResourceUseDetails(99999972,$userId,1,$outputTid,'buyGiftPack');//获得资源上报


        return true;
    }


    /**
     * 礼包购买信息
     * @param $userId
     * @param $platform
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function giftPackInfo($userId, $platform, $reqTime)
    {
        $diamondGiftPackSettings = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_GIFT_PACK, null, true);
        if (!$diamondGiftPackSettings) {
            return array();
        }

        //20190826 zhangpeng

        $platform = GameConst::PLATFORM_TIME_ARRAY[$platform];
        
        /**
         * @var $userGiftPackList GiftPackVoList
         * @var $userGiftPack GiftPackVo
         */
        $userGiftPackList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_GIFT_PACK);

        $userLevel = UserService::get()->getUserLevel($userId);
        foreach ($diamondGiftPackSettings as $giftPackageId => $diamondGiftPackSetting) {
            $userGiftPack = $userGiftPackList->getElement($giftPackageId, false);
            if ($giftPackageId == 50001 && $userGiftPack) {
                $startTime = $userGiftPack->getStartTime();
                $endTime = $userGiftPack->getEndTime();
                if ($startTime == -1 || $endTime == -1 || (($endTime - $startTime) == 86400000)) {
                    $userGiftPack->setStartTime($reqTime);
                    $userGiftPack->setEndTime($reqTime + $diamondGiftPackSetting['timeOfExistence']);
                    $userGiftPackList->updateElement($giftPackageId,$userGiftPack);
                }
            }

            if ($userGiftPack || $userLevel < $diamondGiftPackSetting['level']) {
                continue;
            }

            if (($diamondGiftPackSetting[$platform.'TriggerTime'] && $diamondGiftPackSetting[$platform.'TriggerTime'] != '' && $diamondGiftPackSetting[$platform.'TriggerTime'] != null && !empty($diamondGiftPackSetting[$platform.'TriggerTime']))
                && ($diamondGiftPackSetting[$platform.'EndTime'] && $diamondGiftPackSetting[$platform.'EndTime'] != '' && $diamondGiftPackSetting[$platform.'EndTime'] != null && !empty($diamondGiftPackSetting[$platform.'EndTime']))){
                $startTime = strtotime($diamondGiftPackSetting[$platform.'TriggerTime']);
                $endTime = strtotime($diamondGiftPackSetting[$platform.'EndTime']);
            }
            else{
                $startTime = $diamondGiftPackSetting['triggerTime'];
                $endTime = $diamondGiftPackSetting['endTime'];
            }

            if ($diamondGiftPackSetting['type'] == 1 || $diamondGiftPackSetting['type'] == 7) {
                $startTime = $reqTime;
                $endTime = $reqTime + $diamondGiftPackSetting['timeOfExistence'];
            } else if ($diamondGiftPackSetting['type'] != 4) {
                if ($startTime > $reqTime || $endTime < $reqTime) {
                    continue;
                }
            }
            
            $userGiftPack = new GiftPackVo($userId, $giftPackageId, 0, $startTime, $endTime, true);
            $userGiftPackList->addElement($userGiftPack);
            $userGiftPackList->setElement($giftPackageId, $userGiftPack);
        }
        
        SzPersister::get()->setVoList($userGiftPackList);
        return $userGiftPackList->toArray();
    }

    /**
     * 充值验证接口
     * @param $userId
     * @param $type
     * @param $indexId
     * @param $count
     * @param $reqTime
     * @return array|bool|void
     * @throws SzException
     */
    public function newRechargeOrder($userId,$type,$indexId,$count,$reqTime)
    {
        $orderNo = '';
        //分支验证充值礼包是否符合购买条件
        $results = $this->branchCheck($userId,$type,$indexId,$count,$reqTime);
        //验证玩家余额是否充足&生成订单
        $balance = PlatformService::getPlatformInstanceByUserId($userId)->getAmount($userId);

        if ($results['code'] == 0){
            // 视频卡首次折扣特殊处理
            if ($indexId == 2002){
                $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_VALUE, $indexId, true);
                $num = 0;
                //获取玩家数据
                /**
                 * @var ModuleProfileVo $profile
                 * @var ModuleProfileInfoVoList $profileInfoList
                 */
                $profileInfoList = SzPersister::get()->getVoList($userId, ModuleProfileConst::ORM_NAME_PROFILE_INFO);
                $profileFlag = $profileInfoList->getElement(GameConst::USER_INFO_TYPE_SKIP_VIDEO_CARD_FIRST,false);
                if (!$profileFlag){
                    //获取首次折扣
                    $sale = SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'videoCard', true);
                    $num = ceil($giftConf['price']*($sale['value']/100));
                    if ($num < 10){
                        $num = 10;
                    }
                }
                else{
                    $num =  $giftConf['price'];
                }

                $results['price'] = $num;
            }

            //充值测试白名单
            if (in_array($userId,GameConst::GAME_WEIXIN_TEST_USERID)){
                $results['price'] = 10;
            }

            //生成订单
            $orderNo = $this->genBillNo($userId,$reqTime);
            $endTime = $reqTime + 3600;
            //进行订单下单存储
            /**
             * @var SzMySqlModel $paymentModel
             * @var ModulePaymentOrderVoList $paymentList
             * @var ModulePaymentOrderVo $payment
             */
            $creatId = null;
            $paymentModel = SzPersister::get()->getModel(ModulePaymentConst::ORM_NAME_PAYMENT_ORDER);
            $paymentList = SzPersister::get()->getVoList(null, ModulePaymentConst::ORM_NAME_PAYMENT_ORDER, $userId);
            $payment = new ModulePaymentOrderVo(
                $creatId, // orderId
                $userId, // userId
                $orderNo, // orderNo
                $indexId, // paymentDefId
                $reqTime, // orderTime
                $endTime, // completeTime
                0, // status
                json_encode((string)$orderNo.'-'.$type.'-'.$count), // extra
                $results['price'], // price
                true
            );

            list(, $orderId) = $paymentModel->insert($payment);
            if ($orderId) {
                $payment->setOrderId($orderId);
                $payment->removeInsertFlag();
                $paymentList->setElement($orderId, $payment);
                $paymentModel->setListOfVoCache(array($payment), $paymentList->getList());
            } else {
                $res['code'] = -14;//订单生成失败
            }
        }

        $results['orderNo'] = $orderNo;
        $results['money'] = $balance;

        return $results;
    }

    /**
     * 生成流水号
     * @param int $userId
     * @param int $time
     * @return string
     */
    public function genBillNo($userId, $time)
    {
        return SzUtility::genMd5(uniqid($userId . '_' . $time, false));
    }

    /**
     * 验证逻辑分支
     * @param $userId
     * @param $type
     * @param $indexId
     * @param $count
     * @param $reqTime
     * @return array|bool|void
     * @throws SzException
     */
    public function branchCheck($userId,$type,$indexId,$count,$reqTime){
        $res = array(
            'code' => -1,
            'type' => $type,
            'id' => $indexId,
            'num' => $count,
            'price' => 0
        );

        $changeRes = array();
        $giftConf = array();
        //充值购买物品配置表获取==>1:ft_diamond_gift_pack---2:ft_game_pay---3:ft_diamond_value
        if ($type == 1){//等级段礼包礼包和玫瑰礼包
            $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_GIFT_PACK, $indexId, true);
            if (!empty($giftConf)){
                $changeRes = $this->checkDiamondGiftPack($userId,$giftConf,$reqTime);
            }
        }
        if ($type == 2){//钻石，钻石页签的内容
            $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_PAY, $indexId, true);
            if (!empty($giftConf)){
                $batch = 9;//射爆，这个设计很有特色
                $changeRes = $this->checkGamePay($userId,$giftConf,$reqTime,$batch);
            }
        }
        if ($type == 3){//钻石价值表，金币页签和特惠页签的内容
            $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_VALUE, $indexId, true);
            if (!empty($giftConf)){
                $changeRes = $this->checkDiamondValue($userId,$giftConf);
            }
        }

        if (empty($giftConf)){
            return $res;
        }

        if (!empty($changeRes)){
            $res['code'] = $changeRes['code'];
            $res['price'] = $changeRes['price'];
        }

        return $res;
    }

    /**
     * ft_diamond_gift_pack验证
     * @param $userId
     * @param $giftConf
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function checkDiamondGiftPack($userId,$giftConf,$reqTime)
    {
        $giftPackageId = $giftConf['giftPackageId'];
        $res = array(
            'code' => 0,
            'price' => $giftConf['price'],
        );

        /**
         * @var $userGiftPackList GiftPackVoList
         * @var $userGiftPack GiftPackVo
         */
        $userGiftPackList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_GIFT_PACK);
        $userGiftPack = $userGiftPackList->getElement($giftPackageId, false);

        //获取巡回礼包配置
        $tourGiftConfs = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_TOUR, null, true,false);
        if (!$tourGiftConfs || empty($tourGiftConfs)){
            $res['code'] = -1;//配置不存在
            return $res;
        }

        //获取使用配置
        $key = 0;
        $useConf = array();
        $needGiftArr = array();
        $isTourGift = false;
        foreach ($tourGiftConfs as $id=>$data){
            if (in_array($giftPackageId,$data['giftId'])){
                $key = $id;
                $useConf = $data;
                $needGiftArr = $data['giftId'];
                $isTourGift = true;
                break;
            }
        }

        //非巡回礼包验证
        if (!in_array($giftPackageId,$needGiftArr)){
            if (!$userGiftPack) {
                $res['code'] = -2;//数据不存在
                return $res;
            }

            if ($userGiftPack->getStatus()) {
                $res['code'] = -3;//礼包未购买
                return $res;
            }

            if ($giftConf['type'] != 4) {
                if ($reqTime < $userGiftPack->getStartTime() || $reqTime > ($userGiftPack->getEndTime() + 600)) {
                    $res['code'] = -4;//礼包购买已经过期
                    return $res;
                }
            }
        }

        //巡回礼包验证
        if ($isTourGift && (empty($key) || empty($useConf) || empty($needGiftArr))){
            $res['code'] = -1;//配置不存在
            return $res;
        }

        //返回值
        return $res;
    }

    /**
     * ft_game_pay验证
     * @param $userId
     * @param $giftConf
     * @param $reqTime
     * @param $batch
     * @return array
     */
    public function checkGamePay($userId,$giftConf,$reqTime,$batch)
    {
        $money = $giftConf['price']*10;
        $res = array(
            'code' => 0,
            'price' => $money,
        );

        $activity = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_EVENT, $batch, true);
        $startTime = $activity['startTime'];
        $endTime = $activity['endTime'];

        //平台活动时间区分
        $platform = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_USER_PLATFORM);
        $platformPre = GameConst::PLATFORM_TIME_ARRAY[$platform];
        if ($platform != 'dev'){
            $startTime = strtotime($activity[$platformPre.'TriggerTime']);
            $endTime = strtotime($activity[$platformPre.'EndTime']);
        }

        if ($startTime > $reqTime || $endTime <= ($reqTime + 100)) {
            $res['code'] = -5;//不在活动时间之内
        }

        if ($activity['type'] != ActivityService::ActivityFirstPay) {
            $res['code'] = -6;//非首冲活动类型
        }

        return $res;
    }

    /**
     * ft_diamond_value验证
     * @param $userId
     * @param $giftConf
     * @return array
     * @throws SzException
     */
    public function checkDiamondValue($userId,$giftConf)
    {
        $indexId = $giftConf['indexId'];
        $res = array(
            'code' => 0,
            'price' => $giftConf['price'],
        );

        $diamondSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_VALUE, $indexId, true);
        if (!$diamondSetting) {
            $res['code'] = -1;//配置不存在
            return $res;
        }

        // 每日礼包 && 每周礼包
        if ($diamondSetting['type'] == 6 || $diamondSetting['type'] == 9) {
            /**
             * @var  $dailyGiftPackList DailyGiftPackVoList
             * @var $dailyGiftPack DailyGiftPackVo
             */
            $reqTime = GameService::get()->getReqTime();
            $dailyGiftPackList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_DAILY_GIFT_PACK);
            $dailyGiftPack = $dailyGiftPackList->getElement($indexId,false);
            if (!$dailyGiftPack) {
                $dailyGiftPack = new DailyGiftPackVo($userId,$indexId,0,true);
            }

            $updateTime = $dailyGiftPack->getUpdateTime();
            if($diamondSetting['type'] == 6) {
                if (date('Ymd',$updateTime) == date('Ymd',$reqTime)) {
                    $res['code'] = -7;//今日已经购买
                }
            }

            if($diamondSetting['type'] == 9) {
                $weekday = date('w');
                $weekday = ($weekday + 6) % 7;
                $date = date('Y-m-d',strtotime("-{$weekday} day"));
                $startTime = strtotime($date);
                $endTime = $startTime + 86400 * 7;
                if ($startTime <= $updateTime && $updateTime < $endTime) {
                    $res['code'] = -8;//每周礼包购买时间错误
                }
            }
            return $res;
        }

        // 周年庆
        if ($diamondSetting['type'] == 13) {
            //验证活动是否开启
            $anniversaryAid = ActivityAnniversaryService::get()->getAnniversaryIndexId($userId);
            if ($anniversaryAid) {
                /**
                 * @var AnniversaryStepVoList $anniversaryStepList
                 * @var AnniversaryStepVo $anniversaryStep
                 */
                //获取玩家当前购买阶梯礼包的数据
                $anniversaryStepList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ACTIVITY_ANNIVERSARY_STEP);
                $anniversaryStep = $anniversaryStepList->getElement($anniversaryAid,false);
                if ($anniversaryStep){
                    $step = $anniversaryStep->getBuyStep();
                    if ($step + 10000 != $diamondSetting['order']){
                        $res['code'] = -9;//周年庆阶梯礼包错误
                    }
                }
                else{
                    $res['code'] = -15;//周年庆阶梯礼包数据错误
                }
            }
            else{
                $res['code'] = -13;//周年庆活动数据错误
            }

            return $res;
        }

        //合约系统
        if ($diamondSetting['type'] == 15 || $diamondSetting['type'] == 16) {
            //平台活动时间区分
            $platform = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_USER_PLATFORM);
            $platformPre = GameConst::PLATFORM_TIME_ARRAY[$platform];
            //获取合约系统的相关配置
            $contractConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_EVENT, null, true);
            //当前时间获取
            $nowTime = GameService::get()->getReqTime();
            $useConf = array();
            $contractStart = 0;
            $contractEnd = 0;
            $isNomal = false;
            $isPoint = false;

            foreach ($contractConf as $aid=>$conf){
                if ($conf['functionId'] == GameConst::FUNC_CONTRACT_FUNC){
                    //验证合约期数是否正确
                    if ($platform != 'dev'){
                        $contractStart = strtotime($conf[$platformPre.'TriggerTime']);
                        $contractEnd = strtotime($conf[$platformPre.'EndTime']);
                    }
                    else{
                        $contractStart = $conf['startTime'];
                        $contractEnd = $conf['endTime'];
//test0813
                        $contractStart = strtotime($conf['weixinTriggerTime']);
                        $contractEnd = strtotime($conf['weixinEndTime']);
                    }

                    if ($nowTime >= $contractStart && $nowTime <= $contractEnd){
                        $useConf = $conf;
                        if ($diamondSetting['type'] == 15){
                            $isNomal = true;
                        }
                        if ($diamondSetting['type'] == 16){
                            $isPoint = true;
                        }
                        break;
                    }
                }
            }

            if ($useConf) {
                //获取玩家和合约数据
                /**
                 * @var $contractRewardList ContractRewardVoList
                 * @var $contractReward ContractRewardVo
                 */
                $contractRewardList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_CONTRACT_REWARD);
                $contractReward = $contractRewardList->getElement($useConf['indexId'],false);
                if ($isNomal){
                    if (!$contractReward){
                        $res['code'] = -10;//合约奖励数据错误
                    }
                }

                if ($isPoint){
                    $needPoint = SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'contractLevelup', true);
                    //获取玩家合约数据
                    /**
                     * @var $contractDataList ContractDataVoList
                     * @var $contractData ContractDataVo
                     */
                    $contractDataList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_CONTRACT_DATA);
                    $contractData = $contractDataList->getElement($useConf['indexId'],false);
                    //积分配置处理
                    $point = 0;
                    $pointReward = explode(';',$diamondSetting['specialId']);
                    foreach ($pointReward as $key=>$msg){
                        $specialItem = explode(':',$msg);
                        if ($specialItem[0] == GameConst::SPECIAL_ITEM_TYPE_1){
                            $point += $specialItem[1];
                        }
                    }

                    if ($point){
                        //增加合约积分
                        $hasPoint = $contractData->getNowPoint();
                        $nowLevel = $newLevel  = $contractData->getLevel();
                        if ($hasPoint + $point >= $needPoint['value']){
                            $newLevel = $nowLevel + 1;
                        }
                        //领奖状态
                        if ($newLevel != $nowLevel + 1){
                            $res['code'] = -12;//合约等级错误
                        }
                    }
                    else{
                        $res['code'] = -11;//合约积分礼包配置积分错误
                    }
                }
                return $res;
            }
            else{
                $res['code'] = -1;//配置不存在
                return $res;
            }
        }
        return $res;
    }

    /**
     * 新充值接口
     * @param $userId
     * @param $orderNo
     * @param $reqTime
     * @return array|bool|void
     * @throws SzException
     */
    public function newRechargePay($userId,$orderNo,$reqTime)
    {
        error_log('******************新充值接口Start**********************'."\r\n",3,$_ENV['LOG_ROOT'] . '/recharge.log');
        $res = array(
            'code' => -1,
            'orderNo' => $orderNo,
            'items' => array(),
            'itemStr' => '',
            'payData' =>array()
        );

        //订单查询
        /**
         * @var ModulePaymentOrderVoList $paymentList
         * @var ModulePaymentOrderVo $payment
         */
        error_log('******************订单查询**********************'."\r\n",3,$_ENV['LOG_ROOT'] . '/recharge.log');
        $paymentList = SzPersister::get()->getVoList($userId, ModulePaymentConst::ORM_NAME_PAYMENT_ORDER);
        $paymentDatas = $paymentList->toArray();
        $orderData = array();
        foreach ($paymentDatas as $id=>$data){
            if ($orderNo == $data['platformToken']){
                $orderData = $data;
                break;
            }
        }
        error_log('-------orderData===>'.json_encode($orderData)."\r\n",3,$_ENV['LOG_ROOT'] . '/recharge.log');
        error_log('******************订单查询OK**********************'."\r\n",3,$_ENV['LOG_ROOT'] . '/recharge.log');
        if (empty($orderData)){
            $res['code'] = -16;//订单不存在
            return $res;
        }

        if ($orderData['status'] == 2){
            $res['code'] = -18;//订单已经交付
            return $res;
        }

        $indexId = $orderData['paymentDefId'];
        $orderEndTime = $orderData['completeTime'];
        $extraArr = explode('-',$orderData['extra']);
        $type = $extraArr[1];
        $count = $extraArr[2];
        $cash = (int)$orderData['price'];

        if ($reqTime >= $orderEndTime){
            $res['code'] = -17;//订单已经过期
            return $res;
        }
        error_log('******************订单可用OK**********************'."\r\n",3,$_ENV['LOG_ROOT'] . '/recharge.log');
        $giftConf = array();
        //充值购买物品配置表获取==>1:ft_diamond_gift_pack---2:ft_game_pay---3:ft_diamond_value
        if ($type == 1){//等级段礼包礼包和玫瑰礼包
            $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_GIFT_PACK, $indexId, true);
        }
        if ($type == 2){//钻石，钻石页签的内容
            $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_PAY, $indexId, true);
        }
        if ($type == 3){//钻石价值表，金币页签和特惠页签的内容
            $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_VALUE, $indexId, true);
        }
        if (empty($giftConf)){
            return $res;
        }
        error_log('******************订单可用OK**********************'."\r\n",3,$_ENV['LOG_ROOT'] . '/recharge.log');
        //验证玩家余额是否充足
        $balance = PlatformService::getPlatformInstanceByUserId($userId)->getAmount($userId);
        error_log('-------账户余额balance===>'.$balance."\r\n",3,$_ENV['LOG_ROOT'] . '/recharge.log');
        if ($balance < $cash){
            $res['code'] = -99;//配置不存在
            return $res;
        }

        //扣除相应的金额
        error_log('******************扣除相应的金额Start**********************'."\r\n",3,$_ENV['LOG_ROOT'] . '/recharge.log');
        $payData = PlatformService::getPlatformInstanceByUserId($userId)->safePayment($userId, $cash);
        error_log('******************payData**********************'.json_encode($payData)."\r\n",3,$_ENV['LOG_ROOT'] . '/recharge.log');
        $leftCash = PlatformService::getPlatformInstanceByUserId($userId)->getAmount($userId);
        error_log('******************账户余额leftCash**********************'.$leftCash."\r\n",3,$_ENV['LOG_ROOT'] . '/recharge.log');

        if ($payData['errcode'] != 0){
            $res['code'] = $payData['errcode'];
            $res['payData'] = $payData;
            return $res;
        }
        error_log('******************扣除相应的金额End**********************'."\r\n",3,$_ENV['LOG_ROOT'] . '/recharge.log');
        //进行道具发放
        $results = $this->branchShop($userId,$giftConf,$type,$indexId,$count,$reqTime);
        if ($results['code'] == 0){
            $res['code'] = $results['code'];
            $res['items'] = $results['items'];
            $res['itemStr'] = $results['itemStr'];
            $res['payData'] = $payData;

            //进行订单状态修改
            $payment = $paymentList->getElement($orderData['orderId'],false);
            $payment->setStatus(2);
            $paymentList->updateElement($orderData['orderId'],$payment);
            SzPersister::get()->setVoList($paymentList);
        }
        error_log('******************新充值接口End**********************'."\r\n",3,$_ENV['LOG_ROOT'] . '/recharge.log');
        return $res;
    }

    /**
     * 购买逻辑分支
     * @param $userId
     * @param $giftConf
     * @param $type
     * @param $indexId
     * @param $count
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function branchShop($userId,$giftConf,$type,$indexId,$count,$reqTime){
        $res = array(
            'code' => -1,
            'items' => array(),
            'itemStr' => ''
        );

        $changeRes = array();
        //充值购买物品配置表获取==>1:ft_diamond_gift_pack---2:ft_game_pay---3:ft_diamond_value
        if ($type == 1){//等级段礼包礼包和玫瑰礼包
            $changeRes = $this->buyDiamondGiftPack($userId,$giftConf,$count,$reqTime);
        }
        if ($type == 2){//钻石，钻石页签的内容
            $batch = 9;
            $changeRes = $this->buyGamePay($userId,$giftConf,$reqTime,$batch);
        }
        if ($type == 3){//钻石价值表，金币页签和特惠页签的内容
            $changeRes = $this->buyDiamondValue($userId,$indexId);
        }

        if ($changeRes['code'] == 0){
            $res['code'] = $changeRes['code'];
            $res['items'] = $changeRes['items'];
            $res['itemStr'] = $changeRes['itemStr'];
        }

        return $res;
    }

    /**
     * 等级段礼包礼包和玫瑰礼包
     * @param $userId
     * @param $giftConf
     * @param $count
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function buyDiamondGiftPack($userId,$giftConf,$count,$reqTime){
        $getReward = array();
        $giftPackageId = $giftConf['giftPackageId'];

        $res = array(
            'code' => -1,
            'items' => array(),
            'itemStr' => ''
        );

        /**
         * @var $userGiftPackList GiftPackVoList
         * @var $userGiftPack GiftPackVo
         */
        $userGiftPackList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_GIFT_PACK);
        $userGiftPack = $userGiftPackList->getElement($giftPackageId, false);

        //获取巡回礼包配置
        $tourGiftConfs = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_TOUR, null, true,false);

        //获取使用配置
        $key = 0;
        $useConf = array();
        $needGiftArr = array();
        foreach ($tourGiftConfs as $id=>$data){
            if (in_array($giftPackageId,$data['giftId'])){
                $key = $id;
                $useConf = $data;
                $needGiftArr = $data['giftId'];
                break;
            }
        }

        $isCreat = false;
        if (in_array($giftPackageId,$needGiftArr)){
            if ($userGiftPack) {
                $userGiftPack->setStatus(1);
            }
            else{
                $isCreat = true;
                $userGiftPack = new GiftPackVo(
                    $userId,
                    $giftPackageId,
                    1,
                    $reqTime,
                    0,
                    true
                );
            }
        }

        $outputTid = '';
        $diamond = 0;
        /**
         * @var ModuleItemVoList $itemList
         */
        $itemList = null;
        $index = 0;
        foreach ($giftConf['rewardProps'] as $entityId => $count) {
            $index++;
            if ($giftConf['type'] == 3) {//组合礼包
                $itemList = is_null($itemList) ? SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM) : $itemList;
                list($action, $module, $itemDefId) = EntityService::get()->parseEntityId($entityId);
                if ($action == GameConst::ENTITY_ACTION_GET && $module == GameConst::ENTITY_TYPE_ITEM) {
                    $itemSetting = SzConfig::get()->loadAppConfig(ModuleItemConst::CONFIG_ITEM_DEFS, $itemDefId, true);
                    if ($itemSetting['category'] == GameConst::ITEM_CATEGORY_CULTIVATE_CARD) {
                        $item = $itemList->getElementsByItemDefId($itemDefId);
                        if ($item) {//组合礼包中如果有培育卡且已经获得过则换成对应的钻石
                            $diamond += $giftConf['conversionRatio'][$index - 1];
                            continue;
                        }
                    }
                }
            }
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            $outputTid .= $entityId . ':' . $count . '|';

            //记录所获得物品
            if (!isset($getReward[$entityId])){
                $getReward[$entityId] = $count;
            }
            else{
                $getReward[$entityId] = $getReward[$entityId] + $count;
            }
        }

        foreach ($giftConf['diamond'] as $entityId => $count) {
            if ($entityId == GameConst::ENTITY_ACTION_GET_MONEY && $count > 0) {
                $diamond += $count;
            }
        }

        if ($diamond > 0) {
            GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_GET_MONEY, $diamond, true);
            $outputTid .= GameConst::ENTITY_ACTION_GET_MONEY . ':' . $diamond . '|';

            //记录所获得物品
            if (!isset($getReward[GameConst::ENTITY_ACTION_GET_MONEY])){
                $getReward[GameConst::ENTITY_ACTION_GET_MONEY] = $count;
            }
            else{
                $getReward[GameConst::ENTITY_ACTION_GET_MONEY] = $getReward[GameConst::ENTITY_ACTION_GET_MONEY] + $count;
            }
        }

        if ($isCreat){
            $userGiftPackList->addElement($userGiftPack);
            $userGiftPackList->setElement($giftPackageId, $userGiftPack);
        }
        else{
            $userGiftPack->setStatus(1);
            $userGiftPackList->updateElement($giftPackageId, $userGiftPack);
        }

        SzPersister::get()->setVoList($userGiftPackList);

        if (!empty($key) && !empty($useConf) && !empty($needGiftArr)){
            /**
             * @var TourGiftVoList $tourGiftList
             * @var TourGiftVo $tourGiftInfo
             */
            //获取玩家巡回礼包数据
            $tourGiftList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_TOUR_GIFT);
            $tourGiftInfo = $tourGiftList->getElement($useConf['id'],false);

            if (!$tourGiftInfo){//新建巡回礼包数据
                $tourGiftInfo = new TourGiftVo(
                    $userId,
                    $useConf['id'],
                    json_encode((string)$giftPackageId),
                    json_encode('0,0'),
                    $reqTime,
                    0,
                    true
                );
            }
            else{
                $num = 0;
                $buyInfo = json_decode($tourGiftInfo->getBuySituation());
                if (!empty($buyInfo) || $buyInfo != ''){
                    $bugArr = explode(',',$buyInfo);
                    if (!in_array($giftPackageId,$bugArr)){
                        $num =  count($bugArr) + 1;
                    }else{
                        $num = count($bugArr);
                    }
                }
                if ($num == 0 || $num == 1){
                    $tourGiftInfo->setBuySituation((string)$giftPackageId);
                    $tourGiftInfo->setRewardSituation('0,0');
                }
                else{
                    $tourGiftInfo->setBuySituation($buyInfo.','.$giftPackageId);
                    $getSituation = json_decode($tourGiftInfo->getRewardSituation());
                    $getSituationArr = explode(',',$getSituation);
                    if ($num == 2){
                        if ($getSituationArr[0] != 2){
                            $getSituationArr[0] = 1;
                        }
                    }
                    if ($num == 3){
                        if ($getSituationArr[1] != 2){
                            $getSituationArr[1] = 1;
                        }
                    }

                    $tourGiftInfo->setRewardSituation(implode(',',$getSituationArr));
                }
            }

            if ($tourGiftInfo->isInsert() && !SzUtility::checkArrayKey($useConf['id'], $tourGiftList->getList())) {
                $tourGiftList->addElement($tourGiftInfo);
                $tourGiftList->setElement($useConf['id'],$tourGiftInfo);
            }
            else{
                $tourGiftList->updateElement($useConf['id'],$tourGiftInfo);
            }

            SzPersister::get()->setVoList($tourGiftList);
        }

        // 数据采集:行为
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:cash|action:exchange|',
                'item' => $giftPackageId,
                'value' => 1
            )
        ));

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USE_GOLD, array(
            'clientData' => array(
                'item' => 'cash&exchange&' . $giftPackageId,
                'value' => $giftConf['price']
            )
        ));

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' => $outputTid,
                'item' => 'cash&exchange&' . $giftPackageId,
            )
        ));

        if (!empty($getReward)){
            $res['code'] = 0;
            $res['items'] = $getReward;
        }

        return $res;
    }

    /**
     * 钻石，钻石页签的内容
     * @param $userId
     * @param $giftConf
     * @param $reqTime
     * @param $activityId
     * @return array
     * @throws SzException
     */
    public function buyGamePay($userId,$giftConf,$reqTime,$activityId){
        $res = array(
            'code' => -1,
            'items' => array(),
            'itemStr' => ''
        );

        $totalMoney = 0;
        $money = $giftConf['price']*10;
        $activity = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_EVENT, $activityId, true);

        $gamePaySettings = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_PAY, null, true);
        $reward = array();
        foreach ($gamePaySettings as $gamePaySetting) {
            if ($gamePaySetting['count'] == $money) {
                $reward = $gamePaySetting;
                break;
            }
        }

        if (!$reward) {
            return $res;
        }

        /**
         * @var $activityFirstPayList ActivityFirstPayVoList
         * @var $activityFirstPay ActivityFirstPayVo
         */
        $activityFirstPayList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ACTIVITY_FIRST_PAY);
        $activityFirstPay = $activityFirstPayList->getElement($money,false);
        if ($activityFirstPay) {
            $totalMoney = $money;
//            $activityFirstPay->setBatch($activity['parms']);
            $activityFirstPay->setUpdateTime($reqTime);
        } else {
            $totalMoney = $money*2;
            $activityFirstPay = new ActivityFirstPayVo($userId,$money,$activityId,$reqTime,true);
        }
        if ($activityFirstPay->isInsert() && !SzUtility::checkArrayKey($money, $activityFirstPayList->getList())) {
            $activityFirstPayList->addElement($activityFirstPay);
            $activityFirstPayList->setElement($money,$activityFirstPay);
        } else {
            $activityFirstPayList->updateElement($money,$activityFirstPay);
        }

        GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_GET_MONEY, $totalMoney, true);

        SzPersister::get()->setVoList($activityFirstPayList);

        $res['code'] = 0;
        $res['items'][GameConst::ENTITY_ACTION_GET_MONEY] = $totalMoney;

        return $res;
    }

    /**
     * 钻石价值表，金币页签和特惠页签的内容
     * @param $userId
     * @param $indexId
     * @return array
     * @throws SzException
     */
    public function buyDiamondValue($userId,$indexId){
        $getReward = array();
        $res = array(
            'code' => -1,
            'items' => array(),
            'itemStr' => ''
        );

        $diamondSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_VALUE, $indexId, true);

        // 每日礼包 && 每周礼包
        if ($diamondSetting['type'] == 6 || $diamondSetting['type'] == 9) {
            /**
             * @var  $dailyGiftPackList DailyGiftPackVoList
             * @var $dailyGiftPack DailyGiftPackVo
             */
            $reqTime = GameService::get()->getReqTime();
            $dailyGiftPackList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_DAILY_GIFT_PACK);
            $dailyGiftPack = $dailyGiftPackList->getElement($indexId,false);
            if (!$dailyGiftPack) {
                $dailyGiftPack = new DailyGiftPackVo($userId,$indexId,0,true);
            }

            $dailyGiftPack->setUpdateTime($reqTime);
            if ($dailyGiftPack->isInsert() && !SzUtility::checkArrayKey($indexId, $dailyGiftPackList->getList())) {
                $dailyGiftPackList->addElement($dailyGiftPack);
                $dailyGiftPackList->setElement($indexId,$dailyGiftPack);
            } else {
                $dailyGiftPackList->updateElement($indexId,$dailyGiftPack);
            }
            SzPersister::get()->setVoList($dailyGiftPackList);
        }

        // 周年庆
        if ($diamondSetting['type'] == 13) {
            //验证活动是否开启
            $anniversaryAid = ActivityAnniversaryService::get()->getAnniversaryIndexId($userId);
            if ($anniversaryAid) {
                /**
                 * @var AnniversaryStepVoList $anniversaryStepList
                 * @var AnniversaryStepVo $anniversaryStep
                 */
                //获取玩家当前购买阶梯礼包的数据
                $anniversaryStepList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ACTIVITY_ANNIVERSARY_STEP);
                $anniversaryStep = $anniversaryStepList->getElement($anniversaryAid,false);
                if ($anniversaryStep){
                    $step = $anniversaryStep->getBuyStep();
                    if ($step + 10000 == $diamondSetting['order']){
                        $remarks = '';
                        $serverTime = GameService::get()->getReqTime();
                        $oldGifts = json_decode($anniversaryStep->getRemarks());
                        if (empty($oldGifts) || $oldGifts == ''|| $oldGifts == null || !$oldGifts){
                            $remarks = (string)$indexId;
                        }
                        else{
                            $remarks = $oldGifts.','.$indexId;
                        }

                        //修改数据
                        $anniversaryStep->setBuyStep($step + 1);
                        $anniversaryStep->setUpdateTime($serverTime);
                        $anniversaryStep->setRemarks($remarks);
                        $anniversaryStepList->updateElement($anniversaryAid,$anniversaryStep);
                        SzPersister::get()->setVoList($anniversaryStepList);
                    }
                }
            }
        }

        //合约系统
        if ($diamondSetting['type'] == 15 || $diamondSetting['type'] == 16) {
            //平台活动时间区分
            $platform = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_USER_PLATFORM);
            $platformPre = GameConst::PLATFORM_TIME_ARRAY[$platform];
            //获取合约系统的相关配置
            $contractConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_EVENT, null, true);
            //当前时间获取
            $nowTime = GameService::get()->getReqTime();
            $useConf = array();
            $isNomal = false;
            $isPoint = false;
            $changeTime = GameService::get()->getReqTime();

            foreach ($contractConf as $aid=>$conf){
                if ($conf['functionId'] == GameConst::FUNC_CONTRACT_FUNC){
                    //验证合约期数是否正确
                    if ($platform != 'dev'){
                        $contractStart = strtotime($conf[$platformPre.'TriggerTime']);
                        $contractEnd = strtotime($conf[$platformPre.'EndTime']);
                    }
                    else{
                        $contractStart = $conf['startTime'];
                        $contractEnd = $conf['endTime'];
//test0813
                        $contractStart = strtotime($conf['weixinTriggerTime']);
                        $contractEnd = strtotime($conf['weixinEndTime']);
                    }

                    if ($nowTime >= $contractStart && $nowTime <= $contractEnd){
                        $useConf = $conf;
                        if ($diamondSetting['type'] == 15){
                            $isNomal = true;
                        }
                        if ($diamondSetting['type'] == 16){
                            $isPoint = true;
                        }
                        break;
                    }
                }
            }

            if ($useConf) {
                //获取玩家等级
                $userLevel = UserService::get()->getUserLevel($userId);
                //获取玩家和合约数据
                /**
                 * @var $contractRewardList ContractRewardVoList
                 * @var $contractReward ContractRewardVo
                 */
                $contractRewardList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_CONTRACT_REWARD);
                $contractReward = $contractRewardList->getElement($useConf['indexId'],false);
                if ($isNomal){
                    if ($contractReward){
                        ContractService::get()->setSeniorSituation($userId,$useConf['indexId'],$nowTime);
                    }

                    StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
                        'clientData' => array(
                            'tid' => 'Module:cash|action:contract|',
                            'item' => 'userLevel&'.$userLevel,
                            'value' => 1
                        )
                    ));
                }

                if ($isPoint){
                    $needPoint = SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'contractLevelup', true);
                    //获取玩家合约数据
                    /**
                     * @var $contractDataList ContractDataVoList
                     * @var $contractData ContractDataVo
                     */
                    $contractDataList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_CONTRACT_DATA);
                    $contractData = $contractDataList->getElement($useConf['indexId'],false);
                    //积分配置处理
                    $point = 0;
                    $pointReward = explode(';',$diamondSetting['specialId']);
                    foreach ($pointReward as $key=>$msg){
                        $specialItem = explode(':',$msg);
                        if ($specialItem[0] == GameConst::SPECIAL_ITEM_TYPE_1){
                            $point += $specialItem[1];
                        }
                    }

                    if ($point){
                        //增加合约积分
                        $hasPoint = $contractData->getNowPoint();
                        $totalPoint = $contractData->getPoint();
                        $nowLevel = $newLevel  = $contractData->getLevel();
                        if ($hasPoint + $point >= $needPoint['value']){
                            $contractData->setNowPoint($hasPoint + $point - $needPoint['value']);
                            $contractData->setLevel($nowLevel + 1);
                            $newLevel = $nowLevel + 1;
                        }
                        else{
                            $contractData->setNowPoint($hasPoint + $point);
                        }
                        $contractData->setPoint($totalPoint + $point);
                        $contractData->setUpdateTime($changeTime);
                        $contractDataList->updateElement($useConf['indexId'],$contractData);
                        SzPersister::get()->setVoList($contractDataList);

                        //领奖状态修改
                        if ($newLevel == $nowLevel + 1){
                            $isSenior = $contractReward->getSenior();
                            if ($isSenior){
                                //高级奖励状态解锁
                                $seniorSituation = explode(',',json_decode($contractReward->getSeniorSituation()));
                                $seniorSituation[$newLevel - 1] = 1;
                                $contractReward->setSeniorSituation(implode(',',$seniorSituation));
                            }

                            //普通奖励状态解锁
                            $generalSituation = explode(',',json_decode($contractReward->getGeneralSituation()));
                            $generalSituation[$newLevel - 1] = 1;
                            $contractReward->setGeneralSituation(implode(',',$generalSituation));
                            $contractReward->setUpdateTime($changeTime);

                            $contractRewardList->updateElement($useConf['indexId'],$contractReward);
                            SzPersister::get()->setVoList($contractRewardList);
                        }

                        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
                            'clientData' => array(
                                'tid' => 'Module:cash|action:point|',
                                'item' => 'userLevel&'.$userLevel,
                                'value' => 1
                            )
                        ));

                        $res['itemStr'] = $diamondSetting['specialId'];
                    }
                }
            }
        }

        if ($indexId == 2002){
            //获取玩家数据
            /**
             * @var ModuleProfileVo $profile
             * @var ModuleProfileInfoVoList $profileInfoList
             */
            $profileInfoList = SzPersister::get()->getVoList($userId, ModuleProfileConst::ORM_NAME_PROFILE_INFO);

            $profileFlag = $profileInfoList->getElement(GameConst::USER_INFO_TYPE_SKIP_VIDEO_CARD_FIRST,false);
            if (!$profileFlag){
                //获得标记
                $profileFlag = new ModuleProfileInfoVo(
                    $userId,
                    GameConst::USER_INFO_TYPE_SKIP_VIDEO_CARD_FIRST,
                    1,
                    time(),
                    true
                );
                $profileInfoList->addElement($profileFlag);
                $profileInfoList->setElement(GameConst::USER_INFO_TYPE_SKIP_VIDEO_CARD_FIRST, $profileFlag);
            }
        }

        $outputTid = '';
        foreach ($diamondSetting['item'] as $entityId => $count) {
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            //记录所获得物品
            if (!isset($getReward[$entityId])){
                $getReward[$entityId] = $count;
            }
            else{
                $getReward[$entityId] = $getReward[$entityId] + $count;
            }
            $outputTid .= $entityId . ':' . $count . '|';
        }

        // 数据采集:行为
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:cash|action:exchange|',
                'item' => $indexId,
                'value' => 1
            )
        ));

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USE_GOLD, array(
            'clientData' => array(
                'item' => 'cash&exchange&' . $indexId,
                'value' => $diamondSetting['price']
            )
        ));

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' => $outputTid,
                'item' => 'cash&exchange&' . $indexId,
            )
        ));

        $res['code'] = 0;
        $res['items'] = $getReward;
        return $res;
    }
}
